#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, math

from flask import render_template, request, jsonify
from dbConnection.MysqlConn import Mysql
from app import commom, PAGE_NUM, page_code, upload_files
from . import admin
from app.util import admin_login

reload(sys)
sys.setdefaultencoding('utf8')


# 课程章节列表
@admin.route('/admin/chapter_list.html')
@admin_login
def chapter_list():
    tc = commom.get_teacher()
    zt = commom.get_subject()
    td = commom.get_type()
    return render_template('admin/course/chapter_list.html', tc=tc, zt=zt, td=td)


# 获取数据
@admin.route('/admin/chapter_list_post', methods=['post'])
@admin_login
def chapter_list_post():
    parms = ['cname', 'status', 'uid', 'tid', 'sid', 'cid']
    maps = {}
    for d in parms:
        maps[d] = request.values.get(d)
    p = request.values.get('p', '1')
    c_num = (int(p) - 1) * PAGE_NUM
    sql = "select p.chapterName, p.id, p.clickNum, u.nickName, s.typeName, t.courseName as tname, c.courseName, " \
          "p.url, p.status FROM girl_course_chapter AS p LEFT JOIN girl_teacher AS u ON u.uid = p.uid LEFT JOIN " \
          "girl_subject AS s ON s.sid = p.sid LEFT JOIN girl_type AS t ON t.tid = p.tid LEFT JOIN girl_course AS c " \
          "ON c.cid = p.cid WHERE 1=1"
    sql2 = "select count(p.id) AS con FROM girl_course_chapter AS p LEFT JOIN girl_teacher AS u ON u.uid = p.uid LEFT JOIN " \
          "girl_subject AS s ON s.sid = p.sid LEFT JOIN girl_type AS t ON t.tid = p.tid LEFT JOIN girl_course AS c " \
          "ON c.cid = p.cid WHERE 1=1"
    if maps['cname']:
        sql += " and p.id = '" + maps['cname'] + "' or locate('" + maps['cname'] + "', p.chapterName)>0"
        sql2 += " and p.id = '" + maps['cname'] + "' or locate('" + maps['cname'] + "', p.chapterName)>0"
    if maps['status']:
        sql += " and p.status = '%s'" % maps['status']
        sql2 += " and p.status = '%s'" % maps['status']
    if maps['uid']:
        sql += " and p.uid = '%s'" % maps['uid']
        sql2 += " and p.uid = '%s'" % maps['uid']
    if maps['tid']:
        sql += " and p.tid = '%s'" % maps['tid']
        sql2 += " and p.tid = '%s'" % maps['tid']
    if maps['sid']:
        sql += " and p.sid = '%s'" % maps['sid']
        sql2 += " and p.sid = '%s'" % maps['sid']
    if maps['cid']:
        sql += " and p.cid = '%s'" % maps['cid']
        sql2 += " and p.cid = '%s'" % maps['cid']
    sql += " order by p.id desc limit %d, %d" % (c_num, PAGE_NUM)
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    cont = mysql.getOne(sql2, None)
    mysql.dispose()
    pages = int(math.ceil(cont['con'] / float(PAGE_NUM))) if cont else 0
    route_path = 'get_data'
    html_str = page_code.page_code_html_post(int(p), route_path, pages) if pages > 0 else ''
    if res:
        data = {
            'status':1,
            'res':res,
            'page':html_str,
            'p':p
        }
    else:
        data = {
            'status':2,
            'page':html_str
        }
    return jsonify(data)


# 修改章节状态
@admin.route('/admin/update_chapter_post', methods=['post'])
@admin_login
def update_chapter_post():
    cid = request.values.get('cid')
    pid = request.values.get('pid')
    if pid == '1':
        sql = "update girl_course_chapter set status = 1 WHERE id = '%s'" % cid
    elif pid == '2':
        sql = "update girl_course_chapter set status = 0 WHERE id = '%s'" % cid
    elif pid == '3':
        sql = "delete FROM girl_course_chapter WHERE id = '%s'" % cid
    else:
        return jsonify({'status':0})
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status':1
        }
    else:
        data = {
            'status':0
        }
    return jsonify(data)


# 编辑章节
@admin.route('/admin/chapter_detail.html')
@admin_login
def chapter_detail():
    cid = request.values.get('cid')
    sql = "select p.*, u.nickName, s.typeName, t.courseName as tname, c.courseName FROM girl_course_chapter AS p " \
          "LEFT JOIN girl_teacher AS u ON u.uid = p.uid LEFT JOIN girl_subject AS s ON s.sid = p.sid LEFT JOIN " \
          "girl_type AS t ON t.tid = p.tid LEFT JOIN girl_course AS c ON c.cid = p.cid WHERE p.id = '%s'" % cid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return render_template('admin/course/chapter_detail.html', res=res, url=upload_files.baseUrl)


# 更新章节
@admin.route('/admin/chapter_detail_post', methods=['post'])
@admin_login
def chapter_detail_post():
    cid = request.values.get('cid')
    cname = request.values.get('cname')
    file_apk = request.files.get('file')
    con = get_chapter_detail(cid)
    if con is None:
        return jsonify({'status':0})
    img_url = upload_files.course_img(file_apk, con['tid'], 'audio', con['cid'])
    sql = "update girl_course_chapter SET chapterName = '%s'" % cname
    if img_url:
        sql += ", url = '%s'" % img_url
    sql += " where id = '%s'" % cid
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status':1
        }
    else:
        data = {
            'status':2
        }
    return jsonify(data)


# 添加章节
@admin.route('/admin/chapter_add.html')
@admin_login
def chapter_add():
    tc = commom.get_teacher()
    return render_template('admin/course/chapter_add.html', tc=tc)


# 新增章节
@admin.route('/admin/chapter_add_post', methods=['post'])
@admin_login
def chapter_add_post():
    uid = request.values.get('uid')
    cid = request.values.get('cid')
    chapter = request.values.get('chapter')
    file_apk = request.files.get('file')
    con = get_course_detail(cid)
    if con is None:
        return jsonify({'status':0})
    res = insert_chapter(chapter, uid, con['sid'], con['tid'], con['cid'])
    if res > 0:
        img_url = upload_files.course_img(file_apk, con['tid'], 'audio', con['cid'])
        if img_url:
            update_chapter_url(res, img_url)
        data = {
            'status':1
        }
    else:
        data = {
            'status':0
        }
    return jsonify(data)


# 获取老师的课程
@admin.route('/admin/get_uid_course_post', methods=['post'])
@admin_login
def get_uid_course_post():
    uid = request.values.get('uid')
    sql = "select cid, courseName FROM girl_course WHERE uid = '%s' AND status = 1" % uid
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    mysql.dispose()
    if res:
        data = {
            'status':1,
            'res':res
        }
    else:
        data = {
            'status':0
        }
    return jsonify(data)


# 获取章节信息
def get_chapter_detail(cid):
    sql = "select * FROM girl_course_chapter WHERE id = '%s'" % cid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 获取课程信息
def get_course_detail(cid):
    sql = "select * FROM girl_course WHERE cid = '%s'" % cid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 插入章节
def insert_chapter(cname, uid, sid, tid, cid):
    sql = "insert INTO girl_course_chapter(chapterName, tid, cid, uid, sid, addTime) VALUES ('%s', '%s', '%s', '%s'," \
          " '%s', now())" % (cname, tid, cid, uid, sid)
    mysql = Mysql()
    res = mysql.insertOne(sql, None)
    mysql.dispose()
    return res


# 更新章节地址
def update_chapter_url(cid, url):
    sql = "update girl_course_chapter SET url = '%s' WHERE id = '%s'" % (url, cid)
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    return res
